package com.enjoy.concurrent.ch8;

import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.DelayQueue;

/**
 * 一定时间内供查询结果
 */
@Slf4j
public class CheckJobProcessor {

    //存放任务的队列
    private static DelayQueue<Item<String>> queue = new DelayQueue<>();

    // 单例
    private static class ProcessorHolder {
        public static CheckJobProcessor processor = new CheckJobProcessor();
    }

    public static CheckJobProcessor getInstance() {
        return ProcessorHolder.processor;
    }

    static {
        Thread thread = new Thread(new FetchJob());
        thread.setDaemon(true);
        thread.start();
        log.info("开启过期检查的线程");
    }

    private static class FetchJob implements Runnable {

        private static DelayQueue<Item<String>> queue = CheckJobProcessor.queue;

        //缓存的工作信息
        private static Map<String, JobInfo<?>> jobInfoMap = PendingJobPool.getJobInfoMap();

        @Override
        public void run() {
            while (true) {
                try {
                    Item<String> item = queue.take();
                    String jobName = item.getData();
                    jobInfoMap.remove(jobName);
                    log.info(jobName + " clear!!!");
                } catch (Exception e) {
                    log.error("检查结果出错", e);
                }
            }
        }
    }


    public void putJob(String jobName, long expireTime) {
        Item<String> item = new Item<>(jobName, expireTime);
        queue.offer(item);
        log.info("放入延时队列");
    }

}
